import React, { PureComponent } from 'react';
import styles from './proxy.module.css';
import { getProxyRules, setProxyRules } from '@/utils/url';
import ShowMore from '@/components/showmore';
import { emitter } from '@/utils/emitter';

const { trigger: emit, on } = emitter;
class ProxyAPI extends PureComponent {
  constructor(props) {
    super(props);
    const proxyrules = getProxyRules();
    this.state = {
      storage: Object.keys(getProxyRules()).map(pruleKey => ({
        key: pruleKey,
        value: proxyrules[pruleKey],
        comment: '',
      })),
      expandIndex: [],
      curKey: '',
      canEdit: false,
      editKey: '',
      editValue: '',
      editComment: '',
    };
  }
  updateLog(data = {}) {
    const { key, value } = data;
    const { storage } = this.state;
    this.setState({
      storage: [
        ...storage,
        {
          key,
          value,
        },
      ],
    });
  }
  componentDidMount() {
    on('proxy', this.updateLog);
    on('proxyAdd', () => {
      const { storage } = this.state;
      this.setState({
        storage: [
          ...storage,
          {
            key: '',
            value: '',
          },
        ],
        canEdit: true,
      });
    });
  }
  onSelectTabHandler(tabName) {
    this.props.onSelectTab(tabName);
    this.setState({
      tabName,
      storage: this.getStorage(tabName),
      curKey: '',
    });
  }
  getSubSelected(curTabName) {
    const { storageType } = this.props;
    if (curTabName === storageType) {
      return styles.mdebugSubSelected;
    }
    return;
  }
  onChange(e) {
    this.props.onSetKeywords({
      proxyapi: e.currentTarget.value,
    });
  }
  cellClickHandler(e) {
    this.setState({
      curKey: e.currentTarget.id,
    });
  }
  deleteAll() {
    emit('clearproxy');
    this.setState({
      storage: [],
    });
  }
  delete(flag) {
    const { curKey, storage } = this.state;
    const key = curKey ? curKey : storage[0].key;
    const index = storage.findIndex(item => item.key === key);
    if (flag) return;
    const item = storage[index];
    setProxyRules(item.key, void 0);
    storage.splice(index, 1);
    this.setState({
      storage: [...storage],
      curKey: '',
    });
  }
  edit() {
    const { canEdit, curKey, editKey, editValue, storage, editComment } = this.state;
    const index = storage.findIndex(item => item.key === curKey);
    if (!curKey && !canEdit) return;
    const key = editKey || storage[index].key;
    const value = editValue || storage[index].value;
    const comment = editComment || storage[index].comment;
    if (canEdit) {
      this.delete(true);
      setProxyRules(key, value);
      storage[index].key = key;
      storage[index].value = value;
      storage[index].comment = comment;
      this.setState({
        curKey: '',
      });
    }
    this.setState({
      storage: [...storage],
      canEdit: !canEdit,
    });
  }
  setEditKey(e) {
    this.setState({
      editKey: e.currentTarget.value,
    });
  }
  setEditInput(e, key) {
    this.setState({
      [key]: e.currentTarget.value,
    });
  }

  render() {
    const { storage, curKey, canEdit } = this.state;
    const { keywords = {} } = this.props;
    const { proxyapi: proxyAPIWords } = keywords;
    const hasStorage = storage.length > 0;
    return (
      <div
        className={styles.mdebugActionApplicationCon}
        style={{
          border: hasStorage ? undefined : 'none',
        }}>
        <div className={styles.mdebugFixedHeader}>
          <div className={styles.settings}>
            <input
              type="text"
              placeholder="filter proxy rules"
              onChange={this.onChange.bind(this)}
              className={styles.applicationinput}
              value={proxyAPIWords}
            />
            <div className={styles.allDelete} onClick={() => this.deleteAll()}>
              <img
                src=""
                alt=""
                style={{ width: '14px' }}
              />
            </div>
            <div className={styles.delete} onClick={() => this.delete()}>
              <img
                src=""
                alt=""
                style={{ width: '11px' }}
              />
            </div>
            <div className={styles.mdebugEdit} onClick={() => this.edit()}>
              {canEdit ? (
                <img
                  src=""
                  alt=""
                  className={styles.editImg}
                />
              ) : (
                <img
                  src=""
                  className={styles.editImg}
                  alt=""
                />
              )}
            </div>
          </div>
        </div>
        <div>
          {hasStorage && (
            <ul className={styles.mdebugApplicationHeaderUl}>
              <li className={styles.mdebugApplicationHeaderKeyName}>Domain(原始域名)</li>
              <li className={styles.mdebugApplicationHeaderValueName}>
                Target(代理域名, 修改后请手动刷新页面生效)
              </li>
            </ul>
          )}
          <table
            className={hasStorage ? styles.mdebugApplication : styles.mdebugApplicationNone}
            style={{
              border: hasStorage ? undefined : 'none',
            }}>
            {storage
              .filter(cstorage => {
                const { key, value, comment } = cstorage;
                return (
                  !proxyAPIWords ||
                  key.toLowerCase().indexOf(proxyAPIWords.toLowerCase()) !== -1 ||
                  value.toLowerCase().indexOf(proxyAPIWords.toLowerCase()) !== -1 ||
                  comment.toLowerCase().indexOf(proxyAPIWords.toLowerCase()) !== -1
                );
              })
              .map(storageUnit => {
                const { key, value } = storageUnit;
                return (
                  <tr
                    key={storageUnit.key}
                    id={storageUnit.key}
                    className={`${styles.mdebugApplicationTr} ${curKey === storageUnit.key &&
                      styles.mdebugTrActive}`}
                    onClick={e => this.cellClickHandler(e)}>
                    <td
                      className={styles.mdebugApplicationKeyName}
                      style={{
                        boder: '1px solid  #eee',
                      }}>
                      {key === curKey && canEdit ? (
                        <input
                          type="text"
                          defaultValue={key}
                          className={styles.mdebugEditInput}
                          onChange={e => this.setEditInput(e, 'editKey')}
                        />
                      ) : (
                        <ShowMore key={key}>{key}</ShowMore>
                      )}
                    </td>
                    <td className={styles.mdebugApplicationValueName}>
                      {key === curKey && canEdit ? (
                        <input
                          type="text"
                          defaultValue={value}
                          className={styles.mdebugEditInput}
                          onChange={e => this.setEditInput(e, 'editValue')}
                        />
                      ) : (
                        <ShowMore>{value}</ShowMore>
                      )}
                    </td>
                  </tr>
                );
              })}
          </table>
        </div>
      </div>
    );
  }
}

export default ProxyAPI;
